/*******************************************************************************
 * Copyright (c) 2023. 山东新北洋信息技术股份有限公司 保留所有权利。
 *
 ******************************************************************************/

package online.xuping.thousandsOfWorlds.common;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.view.document.AbstractXlsxView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelView extends AbstractXlsxView {


    /**
     * . 导出 excel
     *
     * @param model    the model Map
     * @param workbook the Excel workbook to populate
     * @param request  in case we need locale etc. Shouldn't look at attributes.
     * @param response in case we need to set cookies. Shouldn't write to it.
     * @throws Exception ,
     */
    @Override
    protected void buildExcelDocument(Map<String, Object> model,
                                      Workbook workbook,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {

        String modelName = (String) model.get("fileName");
        //下载文件的名称
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + modelName + ".xlsx");
        //读取头信息
        List<String> fileHeader = (List<String>) model.getOrDefault("header", null);
        List<List<String>> fileData = (List<List<String>>) model.getOrDefault("data", null);
        Map keyMap = (Map) model.get("keymap");
        if (keyMap == null) {
            keyMap = new HashMap();
        }
        //读取 sheet 的名字
        Sheet sheet = workbook.createSheet("sheetName");
        //处理数据
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < fileHeader.size(); i++) {

            String headerName = fileHeader.get(i);
            if (keyMap.get(headerName) != null) {
                headerName = (String) keyMap.get(headerName);
            }
            headerRow.createCell(i).setCellValue(headerName);
        }

        for (int i = 0; i < fileData.size(); i++) {
            Row dataRow = sheet.createRow(i + 1);
            for (int j = 0; j < fileData.get(i).size(); j++) {
                dataRow.createCell(j).setCellValue(fileData.get(i).get(j));
            }
        }


    }
}
